package com.eningqu.aipen.ui.mine;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSONObject;
import com.blankj.utilcode.util.ApiUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.eningqu.aipen.demo.R;
import com.eningqu.aipen.demo.databinding.ActivityChatBinding;
import com.eningqu.aipen.logic.model.chat.ChatBodyBean;
import com.eningqu.aipen.logic.model.chat.ChatBodyBean.MessagesDTO;
import com.eningqu.aipen.logic.model.chat.ChatResponseBean;
import com.eningqu.aipen.logic.model.chat.ChatTokenBean;
import com.eningqu.aipen.logic.network.Apis;
import com.eningqu.aipen.logic.network.BaseRetrofitUtils;
import com.eningqu.aipen.logic.network.ChatRetrofitUtils;
import com.eningqu.aipen.logic.network.SchedulerTransformer;
import com.eningqu.aipen.ui.adapter.MsgAdapter;
import com.eningqu.aipen.ui.base.BaseActivity;
import com.eningqu.aipen.utils.GlobalConfig;

import java.util.ArrayList;
import java.util.List;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Package:com.eningqu.aipen.ui.mine
 * Author:starr
 * Time:2023/10/3  17:09
 * Description: 百度文心一言接入
 */
public class ChatActivity extends BaseActivity<ActivityChatBinding> {


    //消息实体类
    List<MessagesDTO> messagesDTOList=new ArrayList<>();

    private RecyclerView recyclerView;
    private MsgAdapter adapter;
    public static void startAction(Context context) {
        Intent intent = new Intent(context, ChatActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_chat;
    }

    @Override
    protected void initView() {
        mBinding.setClick(new ChatClick());
        recyclerView=mBinding.rvView;
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        adapter=new MsgAdapter(messagesDTOList);
        recyclerView.setAdapter(adapter);
    }

    @Override
    protected void initData() {
    }

    @Override
    protected void async() {

    }

    @SuppressWarnings("unused")
    public class ChatClick {
        public void getToken(View view) {
            getChatToken();
        }

        /**
         * 开始聊天
         * @param view
         */
        public void chat(View view) {
            if(!TextUtils.isEmpty(mBinding.tvSend.getText())){
                String content=mBinding.edContent.getText().toString();
                messagesDTOList.add(new MessagesDTO("user",content));//用户的问题
                adapter.notifyDataSetChanged();
                adapter.notifyItemInserted(messagesDTOList.size()-1);
                recyclerView.scrollToPosition(messagesDTOList.size()-1);
                mBinding.edContent.setText("");

                //显示占位符加载动画
                mBinding.ivPlaceholder.setVisibility(View.VISIBLE);
                mBinding.llPlaceholder.setVisibility(View.VISIBLE);
                mBinding.tvPlaceholderMsgLeft.animation();
                getChatToken();//请求token
            }else{
                ToastUtils.showShort("请输入问题！");
            }
        }
    }

    /**
     * 获取 Token
     */
    @SuppressLint("CheckResult")
    public void getChatToken() {
        ChatRetrofitUtils.getInstance().create(Apis.class).getBaiduToken(
                GlobalConfig.client_KEY, GlobalConfig.SECRET_KEY,
                "client_credentials")
                .compose(new SchedulerTransformer<>())
                .subscribe(bean ->{
                    if (bean != null) {
                        String accessToken = bean.accessToken;
                        startChat(accessToken);
                    } else {
                        ToastUtils.showShort("body为空");
                    }
                });
    }

    /**
     * 开始 chat
     */
    @SuppressLint("CheckResult")
    public void startChat(String accessToken) {

        //构造对话实体类，后面需要改为根据用户输入动态添加
        ChatBodyBean chatBodyBean = new ChatBodyBean();
        chatBodyBean.messages = messagesDTOList;
        //将参数实体转换为RequestBody
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, JSONObject.toJSONString(chatBodyBean));
        ChatRetrofitUtils.getInstance().create(Apis.class).startChat(body, accessToken)
                .compose(new SchedulerTransformer<>())
                .subscribe(bean -> {
                    String result = bean.result;
                    messagesDTOList.add(new MessagesDTO("assistant",""));//将回答添加到实体中，为下次提问做准备

                    runOnUiThread(() -> {
                        //移除占位view
                        mBinding.llPlaceholder.setVisibility(View.GONE);
                        mBinding.ivPlaceholder.setVisibility(View.GONE);
                        mBinding.tvPlaceholderMsgLeft.stopAnimation();

                    });


                    int length=result.length();
                    final int[] index = {0};
                    new Thread(() -> {
                        while (index[0] <length){
                            try {
                                Thread.sleep(20);
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        messagesDTOList.get(messagesDTOList.size()-1).content=result.substring(0, index[0]);
                                        //刷新列表
                                        adapter.notifyDataSetChanged();
                                        adapter.notifyItemInserted(messagesDTOList.size()-1);
                                        recyclerView.scrollToPosition(messagesDTOList.size()-1);
                                        mBinding.edContent.setText("");
                                    }
                                });
                                index[0]++;
                            }catch (Exception e){
                                e.printStackTrace();
                            }
                        }
                    }).start();
                });

    }



}
